﻿using System;
using Raven.Client;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using Raven.Client.Document;

namespace TinyRadio.Web.Controllers
{
    public abstract class RavenApiController : ApiController
    {
        public IDocumentStore DocumentStore { get { return LazyDocStore.Value; } }

        public IAsyncDocumentSession DocumentSession { get; set; }

        private static readonly Lazy<IDocumentStore> LazyDocStore = new Lazy<IDocumentStore>(() =>
        {
            var docStore = new DocumentStore
            {
                ConnectionStringName = "RavenDB"
            };

            docStore.Initialize();

            return docStore;
        });

        public async override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
        {
            using (DocumentSession = DocumentStore.OpenAsyncSession())
            {
                var result = await base.ExecuteAsync(controllerContext, cancellationToken);

                await DocumentSession.SaveChangesAsync();

                return result;
            }
        }
    }
}